var base_url = getApp().globalData.base_url
var app = getApp();

Page({
  data: {
    selectTime: new Date().getFullYear().toString() + '-' + (new Date().getMonth() + 1).toString(),
    list: [],
    isLoaded: false
  },

  bindMonthChange: function (e) {
    this.setData({
      selectTime: e.detail.value
    })
    this.refresh()
  },


  //发送get请求获取收支记录数据
  onLoad: function () {
    this.getAndSetCategories()
    this.refresh()
  },

  onShow(e) {
    if (this.data.isLoaded) {
      console.log("yes!")
      this.setData({
        list: app.globalData.detailList
      })
    }
  },

  delete(e) {
    var that = this;
    let accountId = e.currentTarget.dataset.accountid
    wx.request({
      url: base_url + '/users/accounts/' + accountId,
      method: 'DELETE',
      header: {
        "content-type": "application/json"
      },
      success(res) {
        if (res.data.resultCode == 200) {
          wx.showToast({
            title: '删除成功',
            icon: 'success',
            duration: 3000
          })
          that.removeByVal(app.globalData.detailList, accountId)
          that.onShow()
        } else {
          wx.showToast({
            title: '删除失败',
            icon: 'error',
            duration: 3000
          })
        }
      },
      fail(res) {
        console.log(res);
      }
    })
  },

  change(e) {
    app.globalData.accountId = e.currentTarget.dataset.accountid
    wx.navigateTo({
      url: '/pages/changeDetails/changeDetails',
    })
  },

  removeByVal(arrylist, val) {
    for (var i = 0; i < arrylist.length; i++) {
      if (arrylist[i].accountId == val) {
        arrylist.splice(i, 1);
        break;
      }
    }
  },

  refresh() {
    // 获取当前月份起始
    var that = this;
    let userId = app.globalData.userId
    let fromTime = new Date(this.data.selectTime)
    let endTime = new Date(fromTime)
    endTime.setMonth(fromTime.getMonth() + 1)
    endTime.setDate(0)
    let url = base_url + '/users/accounts/details/' + userId + '?fromTime=' + fromTime.valueOf() + '&endTime=' + endTime.valueOf()

     //在当前页面显示导航条加载动画
     wx.showNavigationBarLoading(); 
     //显示 loading 提示框。需主动调用 wx.hideLoading 才能关闭提示框
     wx.showLoading({
       title: '加载中...',
     })

    wx.request({
      url: url,
      method: 'GET',
      success(res) {
        if (res.data.resultCode == 200) {
          // TODO 在这里执行一个函数，把这些个ID对应的参数进行转换
          let list = res.data.data
          list.map(item => {
            if (item.accountType == 0) {
              item.type = '收入'
            } else {
              item.type = '支出'
            }
            item.localDate = new Date(item.accountTime).toLocaleDateString()
            item.categoryName = that.getCategoryNameById(item.categoryId)
          })
          app.globalData.detailList = res.data.data
          that.setData({
            list: app.globalData.detailList
          })
          that.data.isLoaded = true
        }
      },
      complete() {
        //隐藏loading 提示框
        wx.hideLoading();
        //隐藏导航条加载动画
        wx.hideNavigationBarLoading();
        wx.stopPullDownRefresh();
      }
    })
  },

  onPullDownRefresh: function () {
    wx.showNavigationBarLoading();
    wx.showLoading({
      title: '刷新中...',
    })
    this.refresh();
  },

  getCategoryNameById(id) {
    let list = app.globalData.categories
    for (let i = 0; i < list.length; i++) {
      if (id == list[i].categoryId) {
        return list[i].categoryName
      }
    }
  },


getAndSetCategories() {
    var that = this;
    this.startLoad()
    wx.request({
        url: base_url + '/admins/categories',
        method: 'GET',
        success(res) {
            if (res.data.resultCode == 200) {
                app.globalData.categories = res.data.data
            }
        },
        complete() {
            that.endLoad()
        }
    })
},

startLoad() {
    //在当前页面显示导航条加载动画
    wx.showNavigationBarLoading();
    //显示 loading 提示框。需主动调用 wx.hideLoading 才能关闭提示框
    wx.showLoading({
        title: '加载中...',
    })
},

endLoad() {
    //隐藏loading 提示框
    wx.hideLoading();
    //隐藏导航条加载动画
    wx.hideNavigationBarLoading();
    wx.stopPullDownRefresh();
},

findCategoryIdByName(categoryName) {
    let categories = app.globalData.categories
    let categoryId;
    for (let i = 0; i < categories.length; i++) {
        if (categoryName == categories[i].categoryName) {
            categoryId = categories[i].categoryId
            break
        }
    }
    return categoryId
}

})